package com.skyline.energy.definition;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

import com.skyline.energy.annotation.Cache;
import com.skyline.energy.exception.DaoGenerateException;
import com.skyline.energy.utils.CommonUtils;

public class CacheDefinition extends BaseCacheDefinition {
	private String pool;
	private String key;
	private String vkey;
	private long expire;

	private boolean isReturnCollection;

	public CacheDefinition(Cache cache, Method method) throws DaoGenerateException {
		init(cache, method);
	}

	private void init(Cache cache, Method method) throws DaoGenerateException {
		pool = cache.pool();
		expire = cache.expire();
		key = cache.key();
		vkey = cache.vkey();

		Class<?>[] paramTypes = method.getParameterTypes();
		Annotation[][] annotations = method.getParameterAnnotations();
		Map<String, Integer> paramIndexes = new HashMap<String, Integer>(8, 1f);
		parseParameterAnnotations(annotations, paramTypes, paramIndexes);

		Class<?> returnType = method.getReturnType();
		
		configCacheKey(cache.key(), cache.vkey(), paramTypes, paramIndexes, returnType);

		checkConfig(returnType);
	}

	private void checkConfig(Class<?> returnType) throws DaoGenerateException {
		isReturnCollection = CommonUtils.isTypeCollection(returnType);
		if (isReturnCollection && StringUtils.isEmpty(vkey)) {
			throw new DaoGenerateException("need vkey in @Cache if returns collection");
		}
	}

	public String getPool() {
		return pool;
	}

	public String getKey() {
		return key;
	}

	public String getVkey() {
		return vkey;
	}

	public long getExpire() {
		return expire;
	}

	public boolean isReturnCollection() {
		return isReturnCollection;
	}

}
